import subprocess
import sys
import os
import sqlite3
from time import sleep
import signal
import subprocess

# 不再需要设置服务器连接环境变量，因为数据采集器已移除

def start_service(command, name):
    """启动服务"""
    try:
        process = subprocess.Popen(command)
        print(f"{name} 已启动，PID: {process.pid}")
        return process
    except Exception as e:
        print(f"启动 {name} 失败: {str(e)}")
        return None

def wait_for_db_init():
    """等待数据库初始化完成"""
    max_attempts = 20
    attempt = 0
    
    print("等待数据库初始化...")
    
    while attempt < max_attempts:
        try:
            # 尝试连接数据库并检查表是否存在
            conn = sqlite3.connect('database/eqsystem.db')
            cursor = conn.cursor()
            
            # 检查数据库大小
            db_size = os.path.getsize('database/eqsystem.db')
            print(f"数据库文件大小: {db_size} 字节")
            
            # 列出所有表
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
            tables = cursor.fetchall()
            print(f"数据库表列表: {[t[0] for t in tables]}")
            
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='sync_log'")
            if cursor.fetchone():
                # 检查表中是否有记录
                cursor.execute("SELECT COUNT(*) FROM sync_log")
                count = cursor.fetchone()[0]
                print(f"同步日志记录数: {count}")
                
                conn.close()
                print("数据库初始化完成!")
                return True
            conn.close()
        except Exception as e:
            print(f"等待数据库错误详情: {str(e)}")
        
        attempt += 1
        print(f"等待数据库初始化... ({attempt}/{max_attempts})")
        sleep(1.5)
    
    print("数据库初始化超时，请确保 Web 应用正常启动")
    return False

def main():
    # 确保日志目录存在
    os.makedirs('logs', exist_ok=True)
    
    # 启动 Web 应用 - 使用模块化的run.py而不是app.py
    web_app = start_service([sys.executable, 'run.py'], 'Web应用')
    print("Web应用已配置为监听所有IP地址 (0.0.0.0:5000)")
    
    try:
        print("\n系统已启动，按Ctrl+C停止服务...\n")
        
        while True:
            sleep(1)
    except KeyboardInterrupt:
        print("\n正在关闭服务...")
        if web_app:
            web_app.terminate()
            try:
                # 等待进程退出，最多等待5秒
                web_app.wait(timeout=5)
            except subprocess.TimeoutExpired:
                # 如果超时，强制结束进程
                if sys.platform == 'win32':
                    web_app.kill()
                else:
                    os.kill(web_app.pid, signal.SIGKILL)
        print("服务已关闭")

if __name__ == '__main__':
    main()